
package com.kanjian.music.fragment;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnTouchListener;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;

import com.android.volley.ServerError;
import com.kanjian.music.R;
import com.kanjian.music.adapter.BannerPagerAdapter;
import com.kanjian.music.adapter.MusicPagerAdapter;
import com.kanjian.music.api.ApiRequestManager;
import com.kanjian.music.constants.IntentConstants;
import com.kanjian.music.entity.Banner;
import com.kanjian.music.network.HttpLoader;
import com.kanjian.music.util.CommonUtil;
import com.kanjian.music.util.PixUtil;
import com.viewpagerindicator.TabPageIndicator;
import com.viewpagerindicator.UnderlinePageIndicator;

/**
 * 音乐
 * 
 * @author xuyanjun@kanjian.com
 */
public class MusicFragment extends Fragment implements LoaderCallbacks<String> {

    private View mRootView;

    private ViewPager mViewPager;

    private ViewPager mBannerViewPager;

    private MusicPagerAdapter mMusicPagerAdapter;

    private BannerPagerAdapter mBannerPagerAdapter;

    private RelativeLayout mMusicIndicatorLayout;

    private TabPageIndicator mMusicViewPagerIndicator;

    private UnderlinePageIndicator mUnderlinePageIndicator;

    public final static int mIndicatorMinHeight = (int) PixUtil.getRawSize(
            TypedValue.COMPLEX_UNIT_DIP, 33);

    public final static int mIndicatorMaxHeight = (int) PixUtil.getRawSize(
            TypedValue.COMPLEX_UNIT_DIP, 163);

    private Timer mBannerTimer;

    private BannerTask mBannerTask;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (mRootView == null) {
            initView(inflater, container);
        }
        return mRootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mRootView != null) {
            ViewGroup parentViewGroup = (ViewGroup) mRootView.getParent();
            if (parentViewGroup != null) {
                parentViewGroup.removeAllViews();
            }
        }
    }

    private void initView(LayoutInflater inflater, ViewGroup container) {
        mRootView = inflater.inflate(R.layout.fragment_music, container, false);
        mViewPager = (ViewPager) mRootView.findViewById(R.id.view_pager);
        mBannerViewPager = (ViewPager) mRootView.findViewById(R.id.banner_pager);

        mMusicIndicatorLayout = (RelativeLayout) mRootView
                .findViewById(R.id.music_indicator_layout);
        mMusicViewPagerIndicator = (TabPageIndicator) mMusicIndicatorLayout
                .findViewById(R.id.music_viewpager_indicator);
        mUnderlinePageIndicator = (UnderlinePageIndicator) mMusicIndicatorLayout
                .findViewById(R.id.music_viewpager_underline_indicator);

        mMusicPagerAdapter = new MusicPagerAdapter(getChildFragmentManager());

        // FIXME test code
        ArrayList<Fragment> list = new ArrayList<Fragment>();
        mBannerPagerAdapter = new BannerPagerAdapter(getChildFragmentManager());
        mBannerViewPager.setOffscreenPageLimit(list.size());
        mBannerViewPager.setAdapter(mBannerPagerAdapter);

        mBannerViewPager.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                    case MotionEvent.ACTION_HOVER_ENTER:
                    case MotionEvent.ACTION_MOVE:
                        stopAutoScroll();
                        break;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_HOVER_EXIT:
                    case MotionEvent.ACTION_OUTSIDE:
                        startAutoScroll();
                        break;
                }
                return false;
            }
        });

        mViewPager.setOffscreenPageLimit(4);
        mViewPager.setAdapter(mMusicPagerAdapter);
        mUnderlinePageIndicator.setViewPager(mViewPager);
        mMusicViewPagerIndicator.setViewPager(mViewPager);
        mUnderlinePageIndicator.setFades(false);
        mMusicViewPagerIndicator.setOnPageChangeListener(mUnderlinePageIndicator);

        // 设置Indicator滚动动画
        mUnderlinePageIndicator.setOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageSelected(int arg0) {
                Fragment currentFragment = mMusicPagerAdapter.getItem(arg0);
                if (currentFragment instanceof MusicSubBaseFragment) {
                    if (((MusicSubBaseFragment) currentFragment).mListView != null) {
                        ((MusicSubBaseFragment) currentFragment).smoothScrollToTop(
                                mIndicatorMaxHeight - mIndicatorMinHeight, mIndicatorMinHeight);
                    }
                }
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });
        startAutoScroll();
        Bundle args = new Bundle();
        args.putSerializable(IntentConstants.HTTPLOADERREQUESTPARAM,
                ApiRequestManager.getBannerRequest());
        getLoaderManager().initLoader(0, args, this);
    }

    public void changeIndicatorHeight(int height) {
        RelativeLayout.LayoutParams params = (LayoutParams) mMusicIndicatorLayout.getLayoutParams();
        int changeHeight = height - mIndicatorMaxHeight;
        if (Math.abs(changeHeight) > mIndicatorMaxHeight - mIndicatorMinHeight) {
            changeHeight = mIndicatorMinHeight - mIndicatorMaxHeight;
        }

        params.topMargin = changeHeight;
        mMusicIndicatorLayout.setLayoutParams(params);
    }

    private void startAutoScroll() {
        if (mBannerTask != null) {
            mBannerTask.cancel();
        }
        if (mBannerTimer != null) {
            mBannerTimer.cancel();
        }
        mBannerTask = new BannerTask();
        mBannerTimer = new Timer();
        mBannerTimer.schedule(mBannerTask, 6000, 6000);
    }

    private void stopAutoScroll() {
        if (mBannerTask != null) {
            mBannerTask.cancel();
            mBannerTask = null;
        }
        if (mBannerTimer != null) {
            mBannerTimer.purge();
            mBannerTimer.cancel();
            mBannerTimer = null;
        }
    }

    public void syncOtherFragmentsListScroll(int firstItem, int y) {
        int length = mMusicPagerAdapter.getCount();
        for (int i = 0; i < length; i++) {
            if (mViewPager.getCurrentItem() == i) {
                continue;
            }
            ((MusicSubBaseFragment) mMusicPagerAdapter.mFragments[i]).syncListViewScroll(firstItem,
                    y);
        }
    }

    class BannerTask extends TimerTask {
        @Override
        public void run() {
            int currentItem = mBannerViewPager.getCurrentItem();
            if (currentItem == mBannerViewPager.getAdapter().getCount() - 1) {
                currentItem = 0;
            } else {
                currentItem++;
            }
            final int page = currentItem;
            if (getActivity() != null) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mBannerViewPager.setCurrentItem(page, true);
                    }
                });
            }
        }
    }

    @Override
    public Loader<String> onCreateLoader(int id, Bundle args) {
        return new HttpLoader(getActivity(), args);
    }

    @Override
    public void onLoadFinished(Loader<String> loader, String data) {
        if (data != null) {
            ArrayList<Banner> list = Banner.getBannerListFromJson(data);
            ArrayList<BannerFragment> fragmentList = new ArrayList<BannerFragment>();
            for (int i = 0; i < list.size(); i++) {
                fragmentList.add(BannerFragment.newInstance(list.get(i)));
            }
            mBannerPagerAdapter.setFragmentList(fragmentList);
        }
    }

    @Override
    public void onLoaderReset(Loader<String> loader) {
    }

}
